import socket

def demo1():
    # 1.创建tcp服务端套接字
    # AF_INET：IPv4
    # AF_INET6：IPv6
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 设置端口号复用（让服务端程序退出后端口立即释放）
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
    # 2.绑定端口号
    server_socket.bind(("", 8989))
    # 3.设置监听
    server_socket.listen(128)
    # 4.等待接收客户端连接
    client_socket, addr_tuple = server_socket.accept()
    print(client_socket)
    print(addr_tuple)
    # 5.接收客户端数据
    client_data = client_socket.recv(1024)
    # 判断接收数据的长度为0时，表示客户端已经下线了
    if len(client_data) == 0:
        print(client_socket, "已经下线了！")
    print(client_data.decode("gbk"))
    # 6.发送数据到客户端
    client_socket.send("hello world".encode("gbk"))
    # 7.关闭访问的客户端套接字
    client_socket.close()
    # 8.关闭服务端套接字
    server_socket.close()

def demo2():
    # 1.创建服务端套接字
    server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    # 2.设置端口服用
    server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,True)
    # 3.绑定端口
    server_socket.bind(("",8989))
    # 4.设置监听
    server_socket.listen(128)
    # 5.等待客户端连接 返回客户端套接字和地址元祖
    client_socet,addr_tuple = server_socket.accept()
    print("地址元组：",addr_tuple)
    print("客户端套接字：",client_socet)
    # 6.接收客户端数据
    data = client_socet.recv(1024)
    str = data.decode('gbk')
    print("接受客户端数据：",str)
    # 7.发送数据到客户端
    client_socet.send("你好呀".encode('gbk'))
    # 8.释放客户端套接字
    client_socet.close()
    server_socket.close()

if __name__ == '__main__':
    demo2()